
const express = require("express");
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const Jimp = require("jimp");
const axios = require("axios");

const app = express();
const port = 3000;
const upload = multer({ dest: "uploads/" });
app.use(express.static("public"));

app.post("/upload", upload.array("images"), async (req, res) => {
  const results = [];
  for (const file of req.files) {
    const ext = path.extname(file.originalname).toLowerCase();
    if (![".jpg", ".jpeg"].includes(ext)) {
      results.push({
        filename: file.originalname,
        status: "✅ 成功",
        device_id: response.data.device_id || "未识别",
        device_style: response.data.device_style || "未识别"
      });
      continue;
    }
    const image = await Jimp.read(file.path);
    await image.quality(80);
    const buffer = await image.getBufferAsync(Jimp.MIME_JPEG);
    if (buffer.length > 10 * 1024 * 1024) {
      results.push({ filename: file.originalname, status: "❌ 大小超过10MB" });
      continue;
    }
    const base64 = `data:image/jpeg;base64,${buffer.toString("base64")}`;
    try {
      const response = await axios.post("http://localhost:5000/api/upload", {
        image_base64: base64,
        upload_time: new Date().toISOString(),
      });
      results.push({ filename: file.originalname, status: "✅ 成功", result: response.data });
    } catch {
      results.push({ filename: file.originalname, status: "❌ 后端错误" });
    }
    fs.unlinkSync(file.path);
  }
  res.json(results);
});

app.listen(port, () => console.log(`前端服务运行 http://localhost:${port}`));
